const inquirer = require("inquirer").default;
const fse = require("fs-extra");
const path = require("path");
const chalk = require("chalk");

// 文件配置项
let options = {};
function main() {
  const { route, page } = options;
  const routesArrReg = /const route = \[[\s\S]*?\]/;
  const pagePath = path.join(__dirname, `../src/pages/${page}`);
  const vuePath = path.join(pagePath, `index.vue`);
  const vueFileName = page.replace(/([A-Z])/g, "$1").toLowerCase();
  const routerPath = path.join(__dirname, `../src/router/route.js`);

  // 新建page目录
  const createPageDir = async () => {
    const isPageExist = await fse.exists(pagePath);
    if (isPageExist) {
      throw new Error("page已存在");
    }
    await fse.mkdir(pagePath);
    return pagePath;
  };

  async function createAddNewRoute() {
    const newRoute = `    {
      path: "${route}",
      name: "${page}",
      component: () => import("@/pages/${page}/index.vue"),
    }`;
    const routeContent = await fse.readFile(routerPath, "utf-8");
    const newStr = routeContent.replace(routesArrReg, (routesStr) => {
      return (
        routesStr.slice(0, -1) + newRoute + "," + "\n" + routesStr.slice(-1)
      );
    });
    await fse.writeFile(routerPath, newStr, "utf-8");
  }

  const createVueFile = (vueFileName) =>
    `<template>
  <div>
      ${vueFileName}
  </div>
</template>

<script setup></script>

<style lang="scss"></style>`;

  // 新建pages下的vue文件，并且写入内容
  const writePageFile = () => {
    return Promise.all([
      fse.writeFile(vuePath, createVueFile(vueFileName), "utf-8"),
      createAddNewRoute(),
    ]);
  };
  createPageDir()
    .then(() => {
      return writePageFile();
    })
    .then(() => {
      console.log(
        chalk.green(
          `新建页面成功,路由为：/${options.route}重启项目及开发机后生效`
        )
      );
    });
}
inquirer
  .prompt([
    {
      type: "input",
      name: "route",
      message: "请输入要注册的路由",
      default: "请输入小写",
      validate(value) {
        return /^[a-z]+$/.test(value);
      },
    },
    {
      type: "input",
      name: "page",
      message: "请输入page中的页面名称(大驼峰形式)",
      validate(value) {
        return /([A-Z][a-z]+)$/.test(value);
      },
    },
  ])
  .then((answers) => {
    options = answers;
    main();
  })
  .catch((err) => {
    console.log(JSON.stringify(err));
  });
